package FanShe5;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestDemo {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
//        测试没有反射
//        Teacher teacher = new Teacher();
//        String typeInstanceof = TestDemo.getTypeInstanceof(teacher);
//        System.out.println("typeInstanceof = " + typeInstanceof);
//
//        Student student = new Student();
//        String typeInstanceof1 = TestDemo.getTypeInstanceof(student);
//        System.out.println("typeInstanceof1 = " + typeInstanceof1);

        //测试反射效果
        Teacher teacher = new Teacher();
        String type = getType(teacher);
        System.out.println("type = " + type);

    }

    /**
     * @param obj
     * @return 不使用反射 常规用法
     */
    public static String getTypeInstanceof(Object obj) {
        if (obj instanceof Student) {
            Student student = (Student) obj;
            String userType = student.getUserType("王航波");
            return userType;
        }
        if (obj instanceof Teacher) {
            Teacher teacher = (Teacher) obj;
            String userType = teacher.getUserType("胡志维");
            return userType;
        }
        return null;
    }

    //反射
    public static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = obj.getClass();//获取反射对象
        Object o = aClass.newInstance();//通过反射对象实例化类对象
        Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke = (String) getUserType.invoke(o, "王明");
        return invoke;
    }
}
